package com.rxnetwork.sample.utils.interceptor;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.GzipSink;
import okio.GzipSource;
import okio.Okio;

/**
 * 接口请求拦截添加base参数
 */
public class AppHeaderInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request oldRequest = chain.request();
        if (oldRequest.body() == null || oldRequest.header("Content-Encoding") != null) {
            return chain.proceed(oldRequest);
        }
        // 添加url后的参数
        HttpUrl.Builder authorizedUrlBuilder = oldRequest
                .url()
                .newBuilder()
                .scheme(oldRequest.url().scheme()).host(oldRequest.url().host());
//                .setEncodedQueryParameter("lversion", "10.0")
//                .setEncodedQueryParameter("token", "token---sadsaff")
//                .setQueryParameter("user", "xiaocode")
//                .setQueryParameter("devices", "android");
        // 新的请求
        Request newRequest = oldRequest.newBuilder()
                .url(authorizedUrlBuilder.build())
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .addHeader("Accept-Encoding", "gzip, deflate")
                .addHeader("Connection", "keep-alive")
                .addHeader("Accept", "*/*")
                .addHeader("Cookie", "add cookies here")
                //若是服务端没有开启gzip则，服务端解析不到
//                .method(oldRequest.method(), gzip(oldRequest.body()))
                .method(oldRequest.method(), oldRequest.body())
                .build();
        Response response = chain.proceed(newRequest);
        MediaType mediaType = response.body().contentType();
        //服务端开启gzip则客户端配置开启gzip
//        String content = unGzip(response.body()).toString();
        String content = response.body().toString();
        if (response.body() != null) {
            return response.newBuilder().body(ResponseBody.create(mediaType, content)).build();
        } else {
            return response;
        }
    }

    //gzip压缩
    private RequestBody gzip(final RequestBody body) {
        return new RequestBody() {
            @Override
            public MediaType contentType() {
                return body.contentType();
            }

            @Override
            public long contentLength() {
                return -1; // 无法知道压缩后的数据大小
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
                body.writeTo(gzipSink);
                gzipSink.close();
            }
        };
    }

    //解压缩
    private ResponseBody unGzip(final ResponseBody body) {
        return new ResponseBody() {

            @Override
            public MediaType contentType() {
                return body.contentType();
            }

            @Override
            public long contentLength() {
                return -1;
            }

            @Override
            public BufferedSource source() {
                return Okio.buffer(new GzipSource(body.source()));
            }
        };
    }
}
